package net.tngou.iask.action.api;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.text.translate.NumericEntityUnescaper;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import net.tngou.iask.action.BaseAction;
import net.tngou.iask.enums.LevelEnum;
import net.tngou.iask.pojo.Main;
import net.tngou.iask.pojo.POJO;
import net.tngou.iask.pojo.User;
import net.tngou.iask.service.UserService;
import net.tngou.iask.util.DigestMD;
import net.tngou.iask.util.OAuthUtil;

/**
 * 用户登录
 * @author tngou@tngou.net
 *
 */
public class LoginApi extends BaseAction {
	@SuppressWarnings("serial")
	@Override
	public void execute() throws ServletException, IOException {
		String account=request.getParameter("account");//账户
		String password=request.getParameter("password");//密码
		String main=request.getParameter("main");//实体
		String save_login=request.getParameter("save_login");//是否在线
		if(!NumberUtils.isNumber(main))
		{
			run_false("请选择登录平台！");return;
		}
		if(isEmpty(account,password,main)&&!NumberUtils.isNumber(main)){
			run_false("请求参数不正确！");return;
		}
		user=new User().get(new HashMap<String,Object>(){{
			put("account", account);
			put("password", DigestMD.MD5(password));//密码做MD5
			put("main", Long.parseLong(main));//转换成 Long
		}});

		if(user!=null)
		{
			if(user.getRole()<0)
			{
				run_false("用户不能登录！");return;
			}
			String access_token = OAuthUtil.Access_token(user.getAccount(), user.getPassword(),user.getMain()); //
			String refresh_token = OAuthUtil.Refresh_token(user.getAccount());
					
			if(save_login==null) //用于兼容web端处理
			{
				response.addAutoLoginCookie(access_token);//临时 Cookie
			}else
			{
				response.addAutoLoginCookie(60*60*24*365, access_token);//保存1年的Cookie
			}	
			UserService service = new UserService();
			service.saveLogin(access_token, refresh_token, user);
			saveLog(LevelEnum.common, user.getAccount()+" 账户登录!");
			user.setAccess_token(access_token);
			user.setRefresh_token(refresh_token);
			session.setUser(user);
			run_success(access_token);
		}else
		{
			run_false("用户验证失败！");
		}
	}
	
	/**
	 * 取得账户对应的实体
	 */
	@SuppressWarnings({ "unchecked", "serial" })
	public void main() {
		String account=request.getParameter("account");
		if(isEmpty(account)){
			run_false("请求参数不正确！");return;
		}
		List<User> list = (List<User>) new User().list(new HashMap<String, Object>(){
			{put("account", account);}
			});
	
		if(list!=null&&!list.isEmpty())
		{
			JSONArray array = new JSONArray();
			list.forEach(e->{
				if(e.getMain()>0)
				{
					Main main = new Main().get(e.getMain());
					if(main!=null)//判断用户实体是否存在
					{						
						array.add(new JSONObject(new HashMap<String, Object>(){
							{
								put("id", e.getMain());
								put("name", main.getName());}
						    }));
					}
				}else
				{
					array.add(new JSONObject(new HashMap<String, Object>(){
						{
							put("id", e.getMain());
							put("name", "系统默认");}
					    }));					
				}
				
			});
			if(array.size()==0){run_false("用户信息错误！");return;}
			printJson(toJsonP(array));return;
			
		}else
		{
			run_false("不存在该用户！");return;
		}
	}
}
